#!/usr/bin/env python3
# @Date    : 2020-07-18
# @Author  : Bright Li (brt2@qq.com)
# @Link    : https://gitee.com/brt2

import os
import json
import logging
from random import randint
from pprint import pprint

import smms2
from util.gitsh import GitRepo
import util.jhead as jhead

logger = logging.getLogger()


def getopt():
    import argparse

    parser = argparse.ArgumentParser("upload_cnblog", description="")
    # parser.add_argument("-f", "--folder", action="store_true", help="将文件夹内的图像重命名")
    return parser.parse_args()

def _format_filename(path_file):
    assert 0, "尚未完成：处理 `git mv` 操作"
    if not os.path.exists(path_file):
        return path_file

    path_, ext = os.path.splitext(path_file)
    filename_base = path_.rsplit("_", 1)
    # 重命名：filename_base + random
    while True:
        suffix = randint(0, 9999)
        path_file = f"{filename_base}_{suffix}{ext}"
        if not os.path.exists(path_file):
            return path_file


class SMMS_Client:
    path_smms_conf = ".smms.json"

    def __init__(self):
        with open(self.path_smms_conf, "r") as fp:
            dict_conf = json.load(fp)
            repo_dir = dict_conf["repo_dir"]
            smms_token = dict_conf.get("smms_token")

        self.git = GitRepo(repo_dir)
        self.smms = smms2.SMMS_v2(repo_dir, smms_token)

    def upload(self):
        if self.git.is_status_mixed():
            print("当前Stage暂存区有文件未更新至最新状态，无法判定用户明确的上传意图，请更新Repo仓库Git状态")
            return

        files_err = {
            "ext_error": set(),
            "too_large": set(),
            "upload_failed": set(),
        }
        not_ext_checked = True
        check_ext = lambda x: os.path.splitext(x)[1] in [".jpg", ".png", ".gif"]

        def try_uploading():
            state = True
            list_newfile = self.git.status("new_added")
            if not list_newfile:
                logger.warning("不存在需要上传的文件")
                return state

            set_exclude = set()
            for set_item in files_err.values():
                set_exclude |= set_item

            list_uploaded = []
            for path_file in set(list_newfile) - set_exclude:
                # 只需要一次
                if not_ext_checked:
                    # 判断后缀
                    if not check_ext(path_file):
                        logger.error(f"不符合图床格式的文件【{path_file}】")
                        files_err["ext_error"].add(path_file)
                        continue

                    # 计算空占比
                    w, h = jhead.get_resolution(path_file)
                    size = jhead.get_size(path_file, unit="B")
                    rate = size / (w * h)
                    if rate > 1:
                        x = input(f"当前图像的空占比过大【{rate}】，是否仍要上传[y/N]: ")
                        if x.upper() != "Y":
                            files_err["too_large"].add(path_file)
                            continue
                try:
                    self.smms.upload(os.path.abspath(path_file))
                except smms2.FileExists:
                    state = False
                    path_new = _format_filename(path_file)
                    os.rename(path_file, path_new)
                except smms2.UploadError:
                    # logger.warning(f"[-] 文件上传失败【{path_file}】")
                    files_err["upload_failed"].add(path_file)
                else:
                    list_uploaded.append(path_file)

            if list_uploaded:
                self.git.add(list_uploaded)
            return state

        while not try_uploading():
            not_ext_checked = False

        for err_type, set_files in files_err.items():
            if set_files:
                print(f"Error Files: {err_type} -->")
                pprint(set_files)

        # 处理数据库
        self.smms.save_data()
        self.git.add(self.smms.path_db)
        self.git.commit(message=None)


if __name__ == "__main__":
    client = SMMS_Client()
    client.upload()
